package com.bdc.whatwhat.activities;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.bdc.whatwhat.R;
import com.bdc.whatwhat.authentification.Facebook;
import com.bdc.whatwhat.fragments.FluxFragment;
import com.bdc.whatwhat.fragments.core.WWFragment;
import com.bdc.whatwhat.modele.MonFlux;
import com.bdc.whatwhat.modele.WhatWhat;
import com.bdc.whatwhat.modele.Whatter;
import com.bdc.whatwhat.session.SessionManager;
import com.bdc.whatwhat.task.FaireWhatWhatTask;
import com.bdc.whatwhat.task.MonFluxTask;
import com.bdc.whatwhat.views.drawer.LeftDrawer;
import com.bdc.whatwhat.views.drawer.RightDrawer;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MainActivity extends SherlockFragmentActivity implements ListView.OnItemClickListener, View.OnClickListener, LeftDrawer.FragmentActiveDelegate, Facebook.FacebookDelegate, MonFluxTask.FluxTaskDelegate {

    WWFragment activeFragment;
    DrawerLayout drawer;
    ActionBarDrawerToggle actionBarDrawerToggle;

    RightDrawer rightDrawer;
    LeftDrawer leftDrawer;

    SessionManager session;

    TextView notifCount;

    int mNotifCount = 0;

    MonFluxTask monFluxTask;

    ScheduledExecutorService scheduler;

    public final static String LAUNCH_NOTIFICATION = "LAUNCH_NOTIFICATION";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getIntent().getExtras() != null && getIntent().getExtras().get(LAUNCH_NOTIFICATION) != null && getIntent().getExtras().getBoolean(LAUNCH_NOTIFICATION)) {
            afficherNotifications(false);
            getIntent().putExtra(LAUNCH_NOTIFICATION, false);
        }

        personnaliserActionBar();

        session = new SessionManager(this);

        setContentView(R.layout.activity_main);

        charger();
        remplir();
        ajouterListeners();

        lancerTacheMiseAJour();
    }

    public void lancerTacheMiseAJour() {
        scheduler =
                Executors.newSingleThreadScheduledExecutor();

        scheduler.scheduleAtFixedRate
                (new Runnable() {
                    public void run() {
                        Log.e("Notify", "update");
                        if (session.getProfil() != null) {
                            // notifyProfilChanged(session.getProfil());

                        }
                        if (session.getToken() != null) {
                            monFluxTask = new MonFluxTask(MainActivity.this);
                            monFluxTask.execute(session.getToken());
                        }
                    }
                }, 0, 30, TimeUnit.SECONDS);
    }

    public void personnaliserActionBar() {

        getSupportActionBar().setIcon(getResources().getDrawable(R.drawable.ic_in_app));
        // Enable ActionBar app icon to behave as action to toggle nav drawer
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        try {
            int titleId = getResources().getIdentifier("action_bar_title", "id",
                    "android");
            TextView yourTextView = (TextView) findViewById(titleId);
            Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Pacifico.ttf");
            yourTextView.setTypeface(typeface);

        } catch (Exception e) {
        }
    }

    private void charger() {

        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        rightDrawer = (RightDrawer) findViewById(R.id.right_drawer);
        leftDrawer = (LeftDrawer) findViewById(R.id.left_drawer);

        if (session.getMonFlux() != null) {
            mNotifCount = session.getMonFlux().getNbNotifications();
            setCount(mNotifCount);
        }
        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, R.drawable.ic_navigation_drawer, R.string.app_name, R.string.app_name) {

            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                supportInvalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                supportInvalidateOptionsMenu();
                rightDrawer.miseAJourListes();

            }

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                super.onDrawerSlide(drawerView, slideOffset);

                //topDrawer.close();

                if (drawerView.getId() == R.id.rightDrawer)
                    drawer.setScrimColor(getResources().getColor(R.color.white20));
                else
                    drawer.setScrimColor(getResources().getColor(R.color.black70));

            }

        };
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        actionBarDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        actionBarDrawerToggle.onConfigurationChanged(newConfig);
    }

    private void remplir() {

    }

    private void ajouterListeners() {
        drawer.setDrawerListener(actionBarDrawerToggle);

        leftDrawer.setFragmentActiveDelegate(this);
        leftDrawer.setActiveFragment(FluxFragment.newInstance());

    }


    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
        openFragment(position);
    }

    private void openFragment(int position) {
        // drawer.closeDrawer(drawerList);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.main, menu);

        View notif = menu.findItem(R.id.notification).getActionView();
        notifCount = (TextView) notif.findViewById(R.id.notif_count);
        notifCount.setText(String.valueOf(mNotifCount));
        if (mNotifCount == 0)
            notif.findViewById(R.id.circle).setVisibility(View.GONE);
        else
            notif.findViewById(R.id.circle).setVisibility(View.VISIBLE);

        notif.setOnClickListener(this);

        return super.onCreateOptionsMenu(menu);
    }

    /**
     * Permet de mettre à jour le badge de demandes
     *
     * @param count
     */
    public void setCount(int count) {
        mNotifCount = count;
        supportInvalidateOptionsMenu();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

            case R.id.badge:
                //Si le menu de gauche est ouvert on le ferme et on ouvre celui de droite
                if (drawer.isDrawerVisible(GravityCompat.START)) {
                    changeStatusDrawer(GravityCompat.START);
                }
                changeStatusDrawer(GravityCompat.END);
                break;
            default:

                //Si le menu de droite est ouvert on le ferme et on ouvre celui de gauche
                if (drawer.isDrawerVisible(GravityCompat.END)) {
                    changeStatusDrawer(GravityCompat.END);
                }

                changeStatusDrawer(GravityCompat.START);
                break;
        }

        return true;
    }

    @Override
    public void setFragmentActive(WWFragment fragmentActive) {
        ajouterFragment(fragmentActive);
    }

    @Override
    public void changeStatusDrawer(int gravity) {
        if (drawer.isDrawerVisible(gravity)) {
            drawer.closeDrawer(gravity);
        } else {
            drawer.openDrawer(gravity);
        }
    }

    public void ajouterFragment(WWFragment fragment) {

        if (activeFragment != null)
            activeFragment.onPause();

        activeFragment = fragment;
        Fragment f = fragment;

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.fragmentLayout, f);
        ft.commit();

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.notification:
                drawer.closeDrawers();
                afficherNotifications(true);
                break;
        }
    }

    public void afficherNotifications(boolean animation) {

        Intent intent = new Intent(this, NotificationsActivity.class);
        startActivity(intent);

        if (!animation)
            this.overridePendingTransition(0, 0);
    }


    @Override
    public void afficherChargement(boolean afficher) {

    }

    @Override
    public void onFluxRecu(MonFlux monFlux) {

        setCount(monFlux.getNbNotifications());
        session.setMonFlux(monFlux);

        notifyProfilChanged(monFlux.getProfil(), monFlux.getFlux());
    }

    @Override
    public void onErreurReseau() {
    }


    @Override
    public void onFacebookConnected(String email, String id, String session, String nom, String prenom) {

    }

    public void notifyProfilChanged(Whatter monProfil, List<WhatWhat> whatWhatList) {

        session.setProfil(monProfil);

        leftDrawer.mettreAJour();

        if (activeFragment.getClass() == FluxFragment.class) {
            ((FluxFragment) activeFragment).mettreAJour(whatWhatList);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        scheduler.shutdown();
    }

    @Override
    public void onStop() {
        super.onStop();
        scheduler.shutdown();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (scheduler.isShutdown())
            lancerTacheMiseAJour();

        if (session != null && session.getMonFlux() != null)
            setCount(session.getMonFlux().getNbNotifications());
    }

    @Override
    public void onBackPressed() {
        if (!activeFragment.onBackPressed()) {
            if (drawer.isDrawerOpen(Gravity.RIGHT))
                drawer.closeDrawer(Gravity.RIGHT);
            else {
                if (activeFragment instanceof FluxFragment) {
                    super.onBackPressed();
                } else {
                    ajouterFragment(new FluxFragment());
                }
            }
        }
    }

}


